package lyw.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import lyw.app.BaseAppV1;
import lyw.bean.UserLoginBean;
import lyw.common.Constant;
import lyw.util.AtguiguUtil;
import lyw.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;


/**
 * @Author lzc
 * @Date 2022/8/25 11:03
 */
public class Dws_02_DwsUserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_02_DwsUserUserLoginWindow().init(
            4004,
            2,
            "Dws_02_DwsUserUserLoginWindow",
            Constant.TOPIC_DWD_TRAFFIC_UV_DETAIL
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {

        // 1. 找到当日登录用户记录和7日回流用户记录
        SingleOutputStreamOperator<UserLoginBean> beanSteam = findUVAndBack(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanSteam);
        // 3. 写出到doris中
        writeToDoris(resultStream);
    }

    private void writeToDoris(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream
                .map(bean -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;  // 转成json的时候, 属性名使用下划线
                    return JSON.toJSONString(bean, config);
                })
//                .print("测试：");
                .addSink(FlinkSinkUtil.getDorisSink("edu.dws_user_user_login_window"));
    }

    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(
        SingleOutputStreamOperator<UserLoginBean> beanSteam) {
        return beanSteam
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserLoginBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserLoginBean>() {
                    @Override
                    public UserLoginBean reduce(UserLoginBean bean1,
                                                UserLoginBean bean2) throws Exception {

                        System.out.println("bean1:" + bean1 + "  |  bean2:" + bean2);
                        bean1.setBackCt(bean1.getBackCt() + bean2.getBackCt());
                        System.out.println("<<bean1>>: " + bean1);
                        return bean1;
                    }
                },
                new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<UserLoginBean> elements,
                                        Collector<UserLoginBean> out) throws Exception {

                        UserLoginBean bean = elements.iterator().next();

                        bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));

                        bean.setCurDate(AtguiguUtil.toDate(System.currentTimeMillis()));

                        out.collect(bean);

                    }
                }
            );
    }

    private SingleOutputStreamOperator<UserLoginBean> findUVAndBack(
            DataStreamSource<String> loginDataStream) {
        return loginDataStream
                .map(JSONObject::parseObject)
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {

                private ValueState<String> lastLoginDateState;

                @Override
                public void open(Configuration parameters) throws Exception {
                    lastLoginDateState =
                            getRuntimeContext().getState(new ValueStateDescriptor<String>("lastLoginDateState", String.class));
                }

                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<UserLoginBean> out) throws Exception {
//                    System.out.println(JSONObject.toJSONString(obj));
                    Long ts = obj.getLong("ts");
                    String thisLoginDate = AtguiguUtil.toDate(ts);
                    // 最后一次登录日期
                    String lastLoginDate = lastLoginDateState.value();

//                    Long uuCt = 0L;
                    Long backCt = 0L;
                    // 如果这次登录日期与最后一次登录日期不相等, 则这次是今天的第一次登录
                    if (!thisLoginDate.equals(lastLoginDate)) {
                        // 今天第一次登录
                        lastLoginDateState.update(thisLoginDate);  // 把状态更新为这次登录到日期
//                        uuCt = 1L;

                        // 判断这个用户是否维基回流用户
                        // 当最后一次登录日期不会空, 表示这个用户不是新登录用户,才有必要判断是否为回流
                        if (lastLoginDate != null) {
                            Long thisLoginTs = AtguiguUtil.toTs(thisLoginDate);
                            Long lastLoginTs = AtguiguUtil.toTs(lastLoginDate);

                            if ((thisLoginTs - lastLoginTs) / 1000 / 60 / 60 / 24 > 7) {
                                backCt = 1L;
                            }
                        }
                    }

                    if (backCt == 1) {
                        out.collect(new UserLoginBean("", "",
                                                      "",
                                                      backCt,
                                                      ts
                        ));

                    }
                }
            });
    }

}






